package admission.ecnu.service;

import java.util.ArrayList;

import org.json.JSONArray;
import org.json.JSONObject;

import admission.ecnu.dao.classInfoDao;
import admission.ecnu.interfaces.IRnsService;
import admission.ecnu.mainservlet.RnsContext;
import admission.ecnu.object.DataManager;
import admission.ecnu.object.OClassInfo;
public class inputClassInfo implements IRnsService {

	//private OClassInfo newClass = null;
	@Override
	public void executeService(RnsContext context) throws Exception {
		/*
		 * 验证用户key值
		 */
		JSONObject obj = context.getJsonRequestObject();
		if(!DataManager.USER_ID.equals(obj.get("key"))){
			JSONObject jsonReturn = new JSONObject();
			jsonReturn.put("returnCode", DataManager.RETURN_WRONGKEY);
			context.setJsonResponseObject(jsonReturn);
			return;
		}
		
		JSONArray objArray = obj.getJSONArray("classInfo");
		
		String[] classStrArray = obj.getString("classInfo").split("$");
		ArrayList<OClassInfo> classList= new ArrayList<OClassInfo>();
		
		for(int i = 0; i< classStrArray.length; i++){
			OClassInfo newClass = new OClassInfo();
			String[] item = classStrArray[i].split(",");
			for(int j = 0; j<item.length; j++){
				String[] keyValue = item[j].split("=");
				if(keyValue[0].equals("classId"))newClass.setClassId(keyValue[1]);
				if(keyValue[0].equals("grade"))newClass.setGrade(keyValue[1]);
				if(keyValue[0].equals("curriculum"))newClass.setCurriculum(keyValue[1]);
				if(keyValue[0].equals("type"))newClass.setType(keyValue[1]);
				if(keyValue[0].equals("teacher"))newClass.setTeacher(keyValue[1]);
				if(keyValue[0].equals("classTime"))newClass.setClassTime(keyValue[1]);
				if(keyValue[0].equals("classroom"))newClass.setClassroom(keyValue[1]);
				if(keyValue[0].equals("isExam"))newClass.setIsExam(keyValue[1]);
				if(keyValue[0].equals("classCapacity"))newClass.setClassroomCapacity(keyValue[1]);
			}
			classList.add(newClass);
			System.out.print("new class"+i+": "+classList.toString());
			
			newClass = null;
		}
		
		new classInfoDao().classInsert(classList);
		
		JSONObject jsonReturn = new JSONObject();
		jsonReturn.put("returnCode", DataManager.RETURN_SUCCESSFUL);
		context.setJsonResponseObject(jsonReturn);
		
	}
}